// pages/achieve/index.js
import AchieveApi from '../../api/achieve'
import FileApi from  '../../api/file'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    achieveInfo:{},
    level: '',
    rank: '',
    showDatePicker: false, // 展示时间选择器
    showLevel: false, // 展示级别选择器
    currentDate: new Date().getTime(),
    maxDate: new Date().getTime(),
    // properties:[],
    properties:[],
    categoryInfo: {},
    needToRemoveFiles: [],
    ranklevels: [{
      values: ["国际级", "国家级", "省级", "市级", "校级", "院级"]
    },
    {
      values: ['特等奖', '一等奖', '二等奖', '三等奖', '优秀奖', '金牌', '银牌', '铜牌']
    }
    ],
      // 格式化时间
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      }
      if (type === 'month') {
        return `${value}月`;
      }
      return value;
    },
    fileList: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.on('acceptItem', function (data) {
      that.setData({
        achieveInfo: data.data,
        level: data.data.level===''?'':data.data.level.split("级")[0] + "级",
        rank: data.data.level.split("级")[1],
      })
    })
    for (let index = 0; index < this.data.achieveInfo.files.length; index++) {
      var aFile = this.data.achieveInfo.files[index];
      var params = {
        id: this.data.achieveInfo.id,
        fileName: aFile.fileName,
        userId: wx.getStorageSync("user").number,
      }
      // 获取文件url
      FileApi.getFileUrl(params).then( ({data}) => {
        if(data.code === 200 ) {
          var file = {
            name: aFile.fileName,
            size: aFile.fileSize,
            url: data.data,
            id: aFile.id,
          }
          that.setData({
            fileList: that.data.fileList.concat(file)
          })
        } else {
          wx.showToast({
            title: data.data,
            icon: 'none'
          })
        }
      })

    }
    var that = this
    AchieveApi.getCategoryInfoByAchieve(this.data.achieveInfo.id).then(({data}) => {
      if (data.code === 200) {
        let propertyValueList = []
        for (let index = 0; index < data.data.properties.length; index++) {
          var ename = data.data.properties[index].ename
          var propertyValue = {
            propertyId: data.data.properties[index].id,
            propertyName: data.data.properties[index].propertyName,
            propertyValue: that.data.achieveInfo[ename],
            achieveId: that.data.achieveInfo.id,
            ename: ename,
            must: data.data.properties[index].must,
          }
          propertyValueList.push(propertyValue)
        }
        that.setData({
          propertyValueList: propertyValueList,
          categoryInfo: data.data.category
        })
      } else {
        wx.showToast({
          title: data.data,
          icon: 'none'
        })
      }
    })
  },
  showDatePicker() {
    this.setData({
      showDatePicker: true
    })
  },
  // 改变时间出发函数
  changeDate(event) {
    this.setData({
      currentDate: event.detail,
      showDatePicker: false
    });
    var date = new Date(this.data.currentDate)
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    this.setData({
      ['achieveInfo.getTime']: Y + M + D,
    })
  },
  // 关闭时间选择器
  closeDatePicker() {
    this.setData({
      showDatePicker: false,
    });
  },
  // 关闭popup
  onClose() {
    this.setData({
      showDatePicker: false,
      showLevel: false,
    });
  },
  // 显示等级选择器
  showPopupLevel() {
    this.setData({
      showLevel: true
    });
  },
  // 确认选择等级函数
  confirmLevelRank({detail}) {
    this.setData({
      level: detail.value[0],
      rank: detail.value[1],
      showLevel: false,
      ['achieveInfo.level']: detail.value[0] + detail.value[1]
    })
  },
  // 当成果编号改变时触发
  changeAchieveId({detail}) {
    this.setData({
      ['achieveInfo.id']: detail
    })
  },
  // 当成果名称改变时触发
  changeAchieveName({detail}) {
    this.setData({
      ['achieveInfo.achieveName']: detail
    })
  },
  // 当专有属性的值改变时触发
  changePropertyValue(e) {
    let index = e.currentTarget.dataset.index
    this.data.propertyValueList[index].propertyValue = e.detail
  },
  beforeRead(event) {
    const {
      file,
      callback
    } = event.detail;
    var suffix = file.name.substring(file.name.lastIndexOf(".") + 1)
    if (file.type !== 'image' && suffix !== 'pdf') {
      wx.showToast({
        title: '请上传图片或pdf',
        icon: 'none',
        mask: false
      })
    } else {
      callback(file.type === 'image' || file.type === 'file');
    }
  },
  afterRead(event) {
    this.setData({
      fileList: this.data.fileList.concat(event.detail.file)
    })
  },
  previewFile(event) {
  },
  deleteFile(event) {
    const index = event.detail.index
    this.data.fileList.splice(index, 1)
    this.setData({
      fileList: this.data.fileList
    })
    for (let index = 0; index < this.data.achieveInfo.files.length; index++) {
      if (event.detail.file.name === this.data.achieveInfo.files[index].fileName
      && event.detail.file.size === this.data.achieveInfo.files[index].fileSize) {
        this.setData({
          needToRemoveFiles: this.data.needToRemoveFiles.concat(event.detail.file.id)
        })
      }
    }
  },
  // 点击完成上传按钮的事件

  gotoUpload() {
    wx.showLoading({
      title: '正在上传...',
    })
    let that = this
    // 先删除文件
    if (that.data.needToRemoveFiles.length > 0) {
      FileApi.removeFiles(that.data.needToRemoveFiles).then(res => {
        if (res.data.code === 200) {
          // 再上传文件
          that.uploadFile()
        } else {
          wx.showToast({
            title: res.data.data,
            icon:　'none'
          })
        }
      })
    } else {
      that.uploadFile()
    }

  },
  uploadFile(){
    var that = this
    if (that.data.needToRemoveFiles.length > 0) {
      wx.uploadFile({
        filePath: that.data.fileList[0].url,
        name: 'file',
        // name: that.data.fileList[0].name,
        url: 'http://127.0.0.1:8090/file/uploadFile',
        // url: 'http://116.204.108.230:8090/file/uploadFile',
        header: { "Content-Type": "multipart/form-data", "Authentication": wx.getStorageSync('token') },
        formData: {
          achieveId: that.data.achieveInfo.id,
          fileName: that.data.fileList[0].name,
        },
        success(res) {
          var fileRes = {}
          fileRes = JSON.parse(res.data)
          if (fileRes.code === 200) {

            // 准备上传的数据
            // 1. achieve
            var achieve = {
              id: that.data.achieveInfo.id,
              categoryId: that.data.categoryInfo.id,
              getTime: that.data.achieveInfo.getTime,
              achieveName: that.data.achieveInfo.achieveName,
              level: that.data.achieveInfo.level,
              avatarUrl: wx.getStorageSync("user").avatarUrl
            }
            // 2. files
            let files = [fileRes.data[0]]
            // 3. propertyValueList
            // for (let index = 0; index < that.data.propertyValueList.length; index++) {
            //   that.data.propertyValueList[index].achieveId = that.data.achieveId
            // }
            var propertyValueList = that.data.propertyValueList
            var achieveVo = {
              achieve,
              files,
              propertyValueList,
            }
            // 数据准备完成，开始上传吧
            AchieveApi.uploadAchieve(achieveVo).then(res => {
              wx.hideLoading()
              if (res.data.code === 200) {
                wx.showToast({
                  title: '上传成功',
                  icon: 'success'
                })
              } else {
                return wx.showToast({
                  title: res.data.data,
                  icon: 'none'
                })
              }
            })

          } else {
            return wx.showToast({
              title: fileRes.data,
              icon: 'none'
            })
          }
        }
      })
    } else {
      // 1. achieve
      var achieve = {
        id: that.data.achieveInfo.id,
        categoryId: that.data.categoryInfo.id,
        getTime: that.data.achieveInfo.getTime,
        achieveName: that.data.achieveInfo.achieveName,
        level: that.data.achieveInfo.level,
        avatarUrl: wx.getStorageSync("user").avatarUrl
      }
      // 2. files
      // let files = []
      // for (let i = 0; i < that.data.fileList.length; i++) {
      //   let guetFile = {
      //     fileName: that.data.fileList[i].name,
      //     fileSize: that.data.fileList[i].size,
      //
      //   }
      // }
      // 3. propertyValueList
      // for (let index = 0; index < that.data.propertyValueList.length; index++) {
      //   that.data.propertyValueList[index].achieveId = that.data.achieveId
      // }
      var propertyValueList = that.data.propertyValueList
      var achieveVo = {
        achieve,
        // files,
        propertyValueList,
      }
      // 数据准备完成，开始上传吧
      AchieveApi.uploadAchieve(achieveVo).then(res => {
        wx.hideLoading()
        if (res.data.code === 200) {
          wx.showToast({
            title: '上传成功',
            icon: 'success'
          })
        } else {
          return wx.showToast({
            title: res.data.data,
            icon: 'none'
          })
        }
      })
    }

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})
